/**
 * [文章分类管理]表单[JS]
 * @param $isCreate 是否新建
 */
var app = function ($isCreate) {

    Vue.component('treeselect', VueTreeselect.Treeselect);
    return new Vue({
        el: '#vueContainer',
        data: {
            loadOver: false,
            detailOver: false,
            settingOver: false,
            setting: {
                pageType: 'form',    // 页面类型
                isCreate: $isCreate, // 添加状态
            },
            form: {
                name: null,
                parent_id: null,
                status: 0,
                is_show: 0,
                sort: 0,
                description: null,
                setting: {
                    open_seo: null,
                    seo_title: null,
                    seo_keywords: null,
                    seo_description: null,
                },
                news_setting: {
                    open_seo: null,
                    seo_title: null,
                    seo_keywords: null,
                    seo_description: null,
                },
                url_type: 0,
                url: null,
                extra_data: [],
                extra_article: [],
                pc_cate_temp: '',
                pc_list_temp: '',
                pc_detail_temp: '',
                mob_cate_temp: '',
                mob_list_temp: '',
                mob_detail_temp: '',

            },
            customErrMsg: {}, // 自定义错误列表
            selectViewDia: false, // 选择模板文件弹出层
            selectViewField: '', // 当前操作选择模板字段
            SelFileDefaultKey: '', // 默认选择键
            category: { // 分类信息
                isInit: false, // 是否已初始化
                list: [], // 分类列表
            },
            activeGroup: 'base', // 活动tab
            pageDialog: {
                show: false,    // 页面 - 是否展示弹出层
                url: '',        // 页面 - 弹出层连接
                loading: false, // 页面 - 弹出层加载中
                isIframe: false // 页面 - 是否[iframe]嵌入
            },
        },
        created: function () {

            // 参数有父级编号
            var parentId = $w.getParams('parentId');
            if (parentId) this.form.parent_id = parentId;

            // 初始化
            this.init();
            // 初始化下设置
            this.getSetting();
            // 初始化、获取详情
            this.initDetail();
            var that = this;
            this.$nextTick(function () {
                that.loadOver = true;
                that.initMainScroll();
            });
        },
        methods: {
            /**
             * 初始化的逻辑
             */
            init: function () {

                var params = $w.getParams();
                // 是否[iframe]嵌入
                this.pageDialog.isIframe = window.self !== window.top;

                var that = this;
                // [嵌入]返回事件监听 直接走自己的返回
                if (this.pageDialog.isIframe) {
                    window.addEventListener("popstate", function($event) {
                        if (that.cancel) that.cancel(); // 返回上一页
                        window.history.forward(-1);     // 清理此页历史记录
                    }, false);
                    window.history.pushState({
                        title: "title", url: "#"
                    }, "title", "#");
                    window.history.forward(1);
                }
            },
            /**
             * 初始化滚动条
             */
            initMainScroll: function () {
                var shadowDom = this.$refs['mainScrollShadow'];
                if (!shadowDom) return false;
                this.$refs.mainScroller.wrap.onscroll = function ($event) {
                    var opacity = 0;
                    opacity = $event['srcElement']['scrollTop'] / 100;
                    opacity = opacity > 0.6 ? 0.6 : opacity
                    shadowDom['$el']['style']['box-shadow'] = '0 5px 15px 0 rgb(204, 204, 204, ' + opacity + ')';
                };
            },
            /**
             * 获取设置
             * @returns {boolean}
             */
            getSetting: function () {
                // 正在加载...
                var loadingInstance = ELEMENT.Loading.service({
                    fullscreen: false,
                    text: '加载中...',
                    customClass: 'z-index-top'
                });
                var that = this;

                // 获取各模块的值
                $w.request({
                    url: $w.getApiUrl('newsCategory.setting'),
                    type: 'get',
                    data: {
                        type: 'form' // 表单页
                    },
                    dataType: 'json',
                    afterCallback: function () {
                        that.$nextTick(function () {
                            // 获取设置
                            that.$refs['selectCate'].loadRootOptions();
                            // 隐藏正在加载
                            loadingInstance.close();
                        });
                    },
                    callback: function (event) {

                        // 失败的返回|提示
                        if (parseInt(event.no) !== 200) {

                            return that.$message({
                                showClose: true,
                                type: 'error',
                                message: event.msg ? event.msg : '操作失败，请稍后尝试'
                            });
                        }

                        // 挨个赋值[setting]中
                        var filters = ['temp_list_name'];
                        for (var i in event.data) {
                            if (!event.data.hasOwnProperty(i)) continue;
                            that.$set(that.setting, i, event.data[i]);

                            // 在过滤列表中进行过滤
                            if ($w.in_array(i, filters)) continue;

                            // 改变键值
                            if (i.indexOf('_list') !== -1) {
                                that.setting[i] = $w.array_index(event.data[i], 'key');
                            }

                            // 默认值
                            if (i.indexOf('default_') !== -1 && that.setting.isCreate) {
                                that.form[i.replace('default_', '')] = that.setting[i];
                            }
                        }

                        that.$nextTick(function () {
                            that.settingOver = true; // 设置加载完毕
                        });
                    }
                });
            },
            /**
             * 获取下详细信息
             */
            initDetail: function () {

                // 正在加载。。
                var loadingInstance = ELEMENT.Loading.service({
                    fullscreen: false,
                    text: '获取中...',
                    customClass: 'z-index-top'
                });
                var that = this;

                // 是新建
                if ($isCreate) {

                    this.detailOver = true; // 详情加载完毕
                    return this.$nextTick(function () {
                        loadingInstance.close(); // 隐藏正在加载
                    });
                }

                // 获取各模块的值
                $w.request({
                    url: $w.getApiUrl('newsCategory.detail'),
                    type: 'get',
                    data: {id: $w.getParams('id')},
                    dataType: "json",
                    afterCallback: function () {
                        that.$nextTick(function () {
                            // 详情加载完毕
                            that.detailOver = true;
                            // 隐藏正在加载
                            loadingInstance.close();
                        });
                    },
                    callback: function (event) {

                        // 失败的返回|提示
                        if (parseInt(event.no) !== 200) {

                            return that.$message({
                                showClose: true,
                                type: 'error',
                                message: event.msg ? event.msg : '操作失败，请稍后尝试'
                            });
                        }

                        that.form = event.data;

                        that.$nextTick(function () {
                            // 初始化编辑器
                            that.$refs['html_editor'].editorSetContent(
                                event.data.description
                            );
                        });
                    }
                });
            },
            /**
             * 返回上一页
             * @param $reloadList 需要加载列表
             */
            cancel: function ($reloadList) {

                // 需要重新加载下列表
                if ($reloadList && this.pageDialog.isIframe && window.parent.instance.getList) {
                    window.parent.instance.getList();
                }

                // 显示脚部 - 当前页面返回
                if (!this.pageDialog.isIframe) {
                    // 非嵌入页面暂不操作 - 可根据逻辑自行修改
                    // // 正在加载。。
                    // var loadingInstance = ELEMENT.Loading.service({
                    //     fullscreen: false,
                    //     text: '返回中...',
                    //                     customClass: 'z-index-top'
                    // });
                    // window.history.back();
                } else {
                    window.parent.instance.pageDialog.show = false;
                }
            },
            /**
             * 去首页
             */
            goToIndex: function () {
                // 父级
                var parent = window.parent.top;
                if (!parent) return false;

                // 父级[vue]对象
                var vueInstance = parent.instance;
                if (!parent || !(typeof vueInstance === 'object')) return false;

                // 键值
                var key = vueInstance.tab.indexKey;
                // 操作点击
                $(parent.document).find('#tab-' + key).click();
            },
            /**
             * 添加|更新
             */
            submit: function () {

                // 强制关闭下全部弹出层
                this.$message.closeAll();
                // 清空错误信息
                this.$refs['ruleForm'].clearValidate();

                var that = this;
                // 清空错误信息
                this.$set(that, 'customErrMsg', {});
                this.$refs['ruleForm'].validate(function (valid, msg) {

                    // 验证不过 - 滚动到错误字段
                    if (!valid) {
                        var first = $w.array_first_key(msg);
                        return $w.scrollToFormItem(false, first);
                    }

                    // 连接
                    var url = that.setting.isCreate ?
                        $w.getApiUrl('newsCategory.create') :
                        $w.getApiUrl('newsCategory.update');

                    // 正在加载。。
                    var loadingInstance = ELEMENT.Loading.service({
                        fullscreen: false,
                        text: '正在提交...',
                        customClass: 'z-index-top'
                    });

                    var form = that.form;
                    form.description = that.$refs['html_editor'].getEditorHtml();

                    $w.request({
                        url: url,
                        type: 'POST',
                        data: form,
                        dataType: "json",
                        afterCallback: function () {
                            that.$nextTick(function () {
                                // 隐藏正在加载
                                loadingInstance.close();
                            });
                        },
                        callback: function (event) {

                            // 失败的返回|提示
                            if (parseInt(event.no) !== 200) {

                                for (var i in event.data.column_error) {
                                    if (!event.data.column_error.hasOwnProperty(i))
                                        continue;
                                    that.$set(that.customErrMsg, i, event.data.column_error[i]);
                                }
                                // 滚动到错误字段
                                $w.scrollToFormItem();
                                return that.$message({
                                    showClose: true,
                                    type: 'error',
                                    message: event.msg ? event.msg : '操作失败，请稍后尝试'
                                });
                            }

                            // 返回上一页
                            that.cancel(true);
                        }
                    });
                });
            },
            /**
             * 加载列表、子集
             * @param $option
             */
            loadChildren: function ($option) {

                // 正在加载...
                var loadingInstance = ELEMENT.Loading.service({
                    fullscreen: false,
                    text: '加载中...',
                    customClass: 'z-index-top'
                });
                var that = this;

                var parentId = 0;
                if ($option.parentNode && $option.parentNode.id) {
                    parentId = $option.parentNode.id;
                }

                // 获取各模块的值
                $w.request({
                    url: $w.getApiUrl('newsCategory.list'),
                    type: 'get',
                    data: {
                        search: {
                            parent_id: parentId,
                            status: this.setting.status_list.open
                        },
                        option: {
                            load_child: true,
                            child_no_del: true,
                            remove_ids: $w.getParams('id')
                        }
                    },
                    dataType: 'json',
                    afterCallback: function () {
                        that.$nextTick(function () {
                            // 隐藏正在加载
                            loadingInstance.close();
                        });
                    },
                    callback: function (event) {

                        // 失败的返回|提示
                        if (parseInt(event.no) !== 200) {

                            return that.$message({
                                showClose: true,
                                type: 'error',
                                message: event.msg ? event.msg : '操作失败，请稍后尝试'
                            });
                        }

                        // 初始化
                        that.category.list.push({
                            id: 0,
                            name: '作为顶级',
                            childrenStates: {isLoading: false},
                        });

                        for (i in event.data.list) {
                            if (!event.data.list.hasOwnProperty(i)) continue;
                            that.category.list.push(event.data.list[i]);
                        }
                        $option.callback();

                        that.$nextTick(function () {
                            // 隐藏正在加载
                            loadingInstance.close();
                            // ☆ 未初始化 ☆
                            var id = that.form.parent_id;
                            if (!that.category.isInit && id) {
                                var node = that.$refs['selectCate'].getNode(id);
                                // 加载特定数据 子集
                                if (node.hadChild) that.$refs['selectCate'].loadChildrenOptions(node);
                                // 打开
                                if (node.hadChild) that.$refs['selectCate'].toggleExpanded(node);
                                // 初始化加载完毕
                                that.category.isInit = true;
                            } else if (!id) {
                                that.form.parent_id = 0;
                            }
                        });
                    }
                });
            },
            /**
             * 获取模板基础路径
             * @param $pathType
             * @returns {string}
             */
            getTempBasePath: function ($pathType) {

                return $pathType.indexOf('pc_') !== -1 ?
                    this.setting.temp_pc_path : this.setting.temp_mobile_path;
            },
            /**
             * 显示选择模板文件弹出层
             */
            showSelectView: function ($field) {

                // 当前操作键
                this.selectViewField = $field;
                // 默认点选键
                this.SelFileDefaultKey = [this.form[this.selectViewField + '_key']];
                // 展示弹出层
                this.selectViewDia = true;

                var that = this;
                that.$nextTick(function () {
                    that.selectTreeItem(that.$refs.selectFile.root.childNodes);
                });
            },
            /**
             * 选择文件弹出层关闭
             */
            selectTempClose: function () {
                this.$set(this.$refs.selectFile.root, 'childNodes', []);
            },
            /**
             * 加载文件列表
             */
            loadFiles: function ($node, $resolve) {

                if ($node['data'] && $node['data']['leaf']) {
                    return this.$set($node, 'loading', false);
                }
                // 加载中
                this.$set($node, 'loading', true);

                var that = this;
                $w.request({
                    url: $w.getApiUrl('newsCategory.getTemp'),
                    type: 'GET',
                    data: {
                        openPath: $node && $node.data ? $node.data.path : this.getTempBasePath(
                            this.selectViewField
                        ),
                    },
                    dataType: "json",
                    afterCallback: function () {
                        that.$nextTick(function () {
                            // 隐藏正在加载
                            that.$set($node, 'loading', false);
                        });
                    },
                    callback: function (event) {

                        // 失败的返回|提示
                        if (parseInt(event.no) !== 200) {
                            for (var i in event.data.column_error) {
                                if (!event.data.column_error.hasOwnProperty(i))
                                    continue;
                                that.$set(that.customErrMsg, i, event.data.column_error[i]);
                            }
                            // 滚动到错误字段
                            $w.scrollToFormItem();
                            return that.$message({
                                showClose: true,
                                type: 'error',
                                message: event.msg ? event.msg : '操作失败，请稍后尝试'
                            });
                        }

                        // 初始化子集
                        if (!$resolve && !$node.data.children) {
                            that.$set($node.data, 'children', []);
                        }
                        for (var x in event.data) {
                            if (!event.data.hasOwnProperty(x)) continue;
                            if (parseInt(event.data[x]['isFolder']) === -1) {
                                event.data[x]['leaf'] = true;
                            } else {
                                event.data[x]['disabled'] = true;
                            }
                        }

                        // 初始化
                        if ($resolve) {
                            $resolve(event.data);
                        } else {
                            // 此处更新要以自定义的id为键值，非tree的id是自定义的id(在ajax返回中的id)
                            that.$refs.selectFile.updateKeyChildren(
                                $node.data.id, event.data
                            );
                            // 展开
                            that.$set($node, 'expanded', true);
                        }

                        that.$nextTick(function () {
                            that.selectTreeItem($node.childNodes);
                        });
                    }
                });
                return false;
            },
            /**
             * 选择文件夹
             */
            selectTreeItem: function ($children) {
                var stage = '', finder = this.form[this.selectViewField] + '/';
                for (var i in $children) {
                    if (!$children.hasOwnProperty(i)) continue;
                    stage = $children[i]['data']['fileName'];

                    // 文件夹打开
                    if (finder.indexOf(stage + '/') !== -1 && !$children[i]['isLeaf']) {

                        // 关闭文件夹
                        this.$set(this.$refs.selectFile.getNode(
                            $children[i]['data']['id']
                        ), 'expanded', false);
                        // 加载文件列表
                        this.loadFiles(this.$refs.selectFile.getNode(
                                $children[i]['data']['id']
                        ));
                        continue;
                    }
                    // 文件点选
                    else if (finder.indexOf(stage) !== -1 && $children[i]['isLeaf']) {
                        this.$set(this.$refs.selectFile.getNode(
                            $children[i]['data']['id']
                        ), 'checked', true);
                    }

                    // 其他都合起来
                    this.$set(this.$refs.selectFile.getNode(
                        $children[i]['data']['id']
                    ), 'expanded', false);
                }
            },
            /**
             * 点选模板文件
             * @param $data
             * @returns {boolean}
             */
            changeSelFile: function ($data) {
                // 已禁用
                if ($data['disabled']) return false;
                // 已点选..
                this.$refs.selectFile.setCheckedNodes([
                    $data
                ]);
            },
            /**
             * 保存当前选择模板文件
             */
            saveSelFile: function () {
                // 检测是否有点选
                var checkedNodes = this.$refs.selectFile.getCheckedNodes();
                if (!checkedNodes || checkedNodes.length < 1 || !checkedNodes[0]) return this.$message({
                    showClose: true,
                    type: 'error',
                    message: '请选择一个模板文件'
                });

                // 取出最后一个并赋值
                checkedNodes = $w.array_end(checkedNodes);
                // 选择的目录 - 替换PC默认路径
                var choosePath = checkedNodes['path'].replace(this.setting.temp_pc_path, '');
                // 选择的目录 - 替换mobile默认路径
                choosePath = choosePath.replace(this.setting.temp_mobile_path, '');
                this.$set(this.form, this.selectViewField, choosePath);
                this.$set(this.form, this.selectViewField + '_key', checkedNodes['id']);

                // 隐藏弹出层
                this.selectViewDia = false;
                // 当前选择 清空
                this.$refs.selectFile.setCheckedKeys([]);
            },
            /**
             * [额外数据]添加一条
             * @param $column
             */
            addRowExtra: function ($column) {
                if ($w.isEmpty(this.form[$column])) {
                    this.$set(this.form, $column, []);
                }

                this.form[$column].push({
                    name: '',
                    text: '',
                    value: ''
                });
            },
            /**
             * [额外数据]清空
             * @param $column
             */
            cleanAllExtra: function ($column) {
                if ($w.isEmpty(this.form[$column])) return this.$message({
                    type: 'error',
                    showClose: true,
                    message: '列表为空无需清除'
                });

                var that = this;
                this.$confirm('此操作将[清空]全部数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function () {

                    that.$set(that.form, $column, []);
                });
            },
            /**
             * [额外数据]删除某条
             * @param $column
             * @param $key
             */
            delRowExtra: function ($column, $key) {

                var that = this;
                this.$confirm('此操作将[删除此条数据]全部数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function () {

                    that.$delete(that.form[$column], $key);
                });
            },
            /**
             * 上移一条数据
             * @param $column
             * @param $key
             */
            upRowValue: function ($column, $key) {

                var stage = $w.dataNoBind(this.form[$column]);
                // 条目总长度
                var dataLength = 1;
                // 对象需要转化下
                if (!stage instanceof Array) {
                    $key = Object.keys($w.dataNoBind(stage)).indexOf($key);
                }

                // 已经是最后一个
                if (parseInt($key) === (dataLength - 1)) {
                    return this.$message({
                        type: 'error',
                        showClose: true,
                        message: '已经是第一个啦'
                    });
                }

                this.$set(this.form, $column, $w.array_sort(stage, $key, $key - 1));
            },
            /**
             * 下移一条数据
             * @param $column
             * @param $key
             */
            downRowValue: function ($column, $key) {

                var stage = $w.dataNoBind(this.form[$column]);
                // 条目总长度
                var dataLength = 0;
                // 对象需要转化下
                if (!stage instanceof Array) {
                    $key = Object.keys($w.dataNoBind(stage)).indexOf($key);
                    dataLength = Object.keys($w.dataNoBind(stage)).length;
                } else {
                    dataLength = stage.length;
                }
                // 已经是最后一个
                if ($key === (dataLength - 1)) {
                    return this.$message({
                        type: 'error',
                        showClose: true,
                        message: '已经是最后一个啦'
                    });
                }

                this.$set(this.form, $column, $w.array_sort(stage, $key, $key + 1));
            },
        },
        watch: {
            /**
             * 连接类型 检测
             * @param $value
             * @returns {*}
             */
            'form.url_type': function ($value) {

                if (!this.settingOver) return false;
                // 站外连接，需要删除模板
                if ($value !== this.setting.url_type_list.site.value) {
                    this.$delete(this.formRules, 'pc_cate_temp');
                    this.$delete(this.formRules, 'pc_list_temp');
                    this.$delete(this.formRules, 'pc_detail_temp');

                    this.$delete(this.formRules, 'mob_cate_temp');
                    this.$delete(this.formRules, 'mob_list_temp');
                    return this.$delete(this.formRules, 'mob_detail_temp');
                }

                // 站内连接，需要配置好模板——pc端
                this.$set(this.formRules, 'pc_cate_temp', {
                    required: true, message: '请完善模板', trigger: 'blur'
                });
                this.$set(this.formRules, 'pc_list_temp', {
                    required: true, message: '请完善模板', trigger: 'blur'
                });
                this.$set(this.formRules, 'pc_detail_temp', {
                    required: true, message: '请完善模板', trigger: 'blur'
                });

                // 站内连接，需要配置好模板——手机端
                this.$set(this.formRules, 'mob_cate_temp', {
                    required: true, message: '请完善模板', trigger: 'blur'
                });
                this.$set(this.formRules, 'mob_list_temp', {
                    required: true, message: '请完善模板', trigger: 'blur'
                });
                return this.$set(this.formRules, 'mob_detail_temp', {
                    required: true, message: '请完善模板', trigger: 'blur'
                });
            },
            /**
             * 检测默认开启SEO
             * @param $value
             */
            'setting.default_open_seo': function ($value) {
                // 无需操作
                if ($w.isEmpty($value) || !this.setting.isCreate) return true;
                // 赋值 基础
                if ($w.isEmpty(this.form.setting.open_seo)) {
                    this.form.setting.open_seo = $value + '';
                }
                // 赋值 文章
                if ($w.isEmpty(this.form.news_setting.open_seo)) {
                    this.form.news_setting.open_seo = $value + '';
                }
            }
        },
        computed: {
            /**
             * 基础数据SEO是否开启
             * @returns {boolean}
             */
            openSeo: function () {

                if (!this.settingOver) return false;

                return +this.form.setting.open_seo === +this.setting.open_seo_list.open.value;
            },
            /**
             * 文章数据SEO是否开启
             * @returns {boolean}
             */
            openNewsSeo: function () {

                if (!this.settingOver) return false;

                return +this.form.news_setting.open_seo === +this.setting.open_seo_list.open.value;
            },
            /**
             * Form表单规则
             * @returns {*}
             */
            formRules: function () {
                if (!this.detailOver) return {};
                return {
                    name: [
                        {required: true, message: '请完善名称', trigger: 'blur'}
                    ],
                    parent_id: [
                        {required: true, message: '请完善上级编号', trigger: 'blur'}
                    ],
                    status: [
                        {required: true, message: '请完善状态', trigger: 'blur'}
                    ],
                    is_show: [
                        {required: true, message: '请完善是否显示', trigger: 'blur'}
                    ],
                    sort: [
                        {required: true, message: '请完善排序', trigger: 'blur'},
                        {
                            validator: $w.validateNumRange, message: false, trigger: 'blur',
                            max: this.setting.max_sort, min: this.setting.min_sort
                        },
                    ],
                    open_seo: [
                        {required: true, message: '请完善是否开启SEO', trigger: 'blur'}
                    ],
                    url_type: [
                        {required: true, message: '请完善链接类型', trigger: 'blur'}
                    ],
                    pc_cate_temp: [
                        {required: true, message: '请完善模板', trigger: 'blur'}
                    ],
                    pc_list_temp: [
                        {required: true, message: '请完善模板', trigger: 'blur'}
                    ],
                    pc_detail_temp: [
                        {required: true, message: '请完善模板', trigger: 'blur'}
                    ],
                    mob_cate_temp: [
                        {required: true, message: '请完善模板', trigger: 'blur'}
                    ],
                    mob_list_temp: [
                        {required: true, message: '请完善模板', trigger: 'blur'}
                    ],
                    mob_detail_temp: [
                        {required: true, message: '请完善模板', trigger: 'blur'}
                    ],
                };
            }
        }
    });
};
